﻿using System;
using System.Collections.Generic;
using System.Text;
using _18miljard.Config;

namespace _18miljard.Db
{
	public class DbUtils
	{
		public static void Compact(MiljardDb db)
		{
			ConnectionParameters connectionParameters = DbUtils.GetConnectionParameters(db);
			ConnectionParameters tempParameters = DbUtils.GetConnectionParameters(MiljardDb.Temporary);

			object [] oParams = new object[] {connectionParameters.ConnectionStringWithPhysicalDbPath, tempParameters.ConnectionStringWithPhysicalDbPath};

			object objJRO = Activator.CreateInstance(Type.GetTypeFromProgID("JRO.JetEngine"));

			objJRO.GetType().InvokeMember("CompactDatabase", System.Reflection.BindingFlags.InvokeMethod, null, objJRO, oParams);

			System.Runtime.InteropServices.Marshal.ReleaseComObject(objJRO);

			objJRO = null;

			string origDb = connectionParameters.PhysicalDbPath;
			string tmpDb = tempParameters.PhysicalDbPath;

			System.IO.File.Delete(origDb);
			System.IO.File.Move(tmpDb, origDb);
		}

		public static ConnectionParameters GetConnectionParameters(MiljardDb db)
		{
			ConnectionParameters connectionParameters;

			switch (db)
			{
				case MiljardDb.Miljard: connectionParameters = WebConfig.ConnectionParameters;
					break;
				case MiljardDb.MiljardAd: connectionParameters = WebConfig.AdConnectionParameters;
					break;
				case MiljardDb.MiljardMail: connectionParameters = WebConfig.MailConnectionParameters;
					break;
				case MiljardDb.Temporary: connectionParameters = WebConfig.TempConnectionParameters;
					break;
				default: connectionParameters = WebConfig.ConnectionParameters;
					break;
			}

			return connectionParameters;
		}
	}
}
